package config

import (
	"github.com/pelletier/go-toml/v2"
	"github.com/spf13/viper"
	"os"
	"path"
	"v3workshop/pkg/util"
)

type Config struct {
	SourcePath string `json:"sourcePath"`
	TargetPath string `json:"targetPath"`
}

type Manager struct {
	*Config
	Path string
}

func NewManager() *Manager {
	return &Manager{
		Path:   viper.GetString("configPath"),
		Config: new(Config),
	}
}

func (m *Manager) Load() error {
	f, err := os.Open(m.Path)
	if err != nil {
		return err
	}
	defer f.Close()
	return toml.NewDecoder(f).Decode(m.Config)
}

func (m *Manager) Save() error {
	err := m.ensureInitFile()
	if err != nil {
		return err
	}
	f, err := os.Create(m.Path)
	if err != nil {
		return err
	}
	defer f.Close()
	return toml.NewEncoder(f).Encode(m.Config)
}

func (m *Manager) ensureInitFile() error {
	dir := path.Dir(m.Path)
	if !util.IsFileExists(dir) {
		err := os.MkdirAll(dir, os.ModePerm)
		if err != nil {
			return err
		}
	}
	return nil
}
